package org.xhy.hrm.detailService;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.xhy.hrm.asserts.GlobleAssert;
import org.xhy.hrm.domain.LoginUser;
import org.xhy.hrm.domain.Permission;
import org.xhy.hrm.mapper.LoginUserMapper;
import org.xhy.hrm.mapper.PermissionMapper;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        GlobleAssert.hasText(username,"用户名不能为空！");
        LoginUser loginUser = loginUserMapper.selectByName(username);
        GlobleAssert.isNotNull(loginUser,"用户名不存在！");
        List<Permission> permissions = permissionMapper.selectByUserId(loginUser.getId());

        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> {
            return new SimpleGrantedAuthority(permission.getSn());
        }).collect(Collectors.toList());

        String password = loginUser.getPassword();
        //隐私，密码设置为空
        loginUser.setPassword(null);
        //把loginUser转成JSON返回给UserDetails
        return new User(JSON.toJSONString(loginUser),password,authorities);
    }
}
